/**
 * 
 */
package de.szut.dqi10.brailletouchscreenreader.display;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import de.szut.brailletouchscreenreader.R;

/**
 * An adaptation of the FileChooser Activity found under 
 * http://android-er.blogspot.de/2010/01/implement-simple-file-explorer-in.html
 * Used for the Choose File Settings Dialog
 * @author Marco Jedzig, Simon Grafenhorst, Felix Pusch
 *
 */
public class BrailleFileChooserActivity extends ListActivity implements FilenameFilter {

	private static final String FILETYPE_REGEX = ".+[.](txt|rtf)";
	private static final String TAG = "BrailleFileChooserActivity";
	private final String DIRECTORY_UP = "../";
	public static final String FILE_INTENT_EXTRA_TAG = "file";
	
	private List<String> item = null;
	private List<String> path = null;
	private String root;
	private TextView title;
	private FileNameComparator comparator;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		Log.i(TAG, "Created: " + this.toString());
		
		setContentView(R.layout.activity_braillefilechooser);
		title = (TextView) findViewById(R.id.title);

		root = Environment.getExternalStorageDirectory().getPath();
		comparator = new FileNameComparator();
		moveDirectory(root);
	}

	/**
	 * Move the currently displayed directory to the given directory.
	 * Also updates the displayed directory to make sure it is actually displayed.
	 * @param dirPath the directory to move to
	 */
	private void moveDirectory(String dirPath) {
		title.setText("Location: " + dirPath);
		item = new ArrayList<String>();
		path = new ArrayList<String>();
		File f = new File(dirPath);
		File[] files = f.listFiles(this);

		//Get all files
		for (int i = 0; i < files.length; i++) {
			File file = files[i];
			path.add(file.getPath());
			if (file.isDirectory()) {
				item.add(file.getName() + "/");
			}
			else {
				item.add(file.getName());
			}
		}
		
		//Sort them with the comparator
		Collections.sort(item, comparator);
		Collections.sort(path, comparator);
		
		//Add directory up and move to root functionality
		if (!dirPath.equals(root)) {
			item.add(0, root);
			path.add(0, root);
			item.add(1, DIRECTORY_UP);
			path.add(1, f.getParent());
		}

		//Display
		ArrayAdapter<String> fileList =
				new ArrayAdapter<String>(this, R.layout.activity_braillefilechooser_row, item);
		setListAdapter(fileList);
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Log.i(TAG, "Position clicked: " + position);
		
		File file = new File(path.get(position));

		if (file.isDirectory()) {
			if (file.canRead()) {
				Log.i(TAG, "Moving to Directory: " + file.getName());
				moveDirectory(path.get(position));
			} else {
				Log.e(TAG, "Can't read Directory: " + file.getAbsolutePath());
			}
		} else {
			Log.i(TAG, "File clicked: " + file.getAbsolutePath());
			//If we have not clicked on a Directory we have clicked a file
			//End activity and return the File as an Extra
			Intent returnIntent = new Intent();
			returnIntent.putExtra(FILE_INTENT_EXTRA_TAG, file.getAbsolutePath());
			setResult(RESULT_OK,returnIntent);   
			Log.i(TAG, "Closing BrailleFileChooserActivity now.");
			finish(); //Close this activity
		}
	}

	@Override
	public boolean accept(File dir, String filename) {
		//Hidden and unreadable directory will not be accepted
		if (dir.isHidden() || !dir.canRead()) {
			return false;
		}
		//Return true if we have a directory 
		//or a file that matches the accepted filetypes
		return Pattern.matches(FILETYPE_REGEX, filename) || dir.isDirectory();
	}
	
	/**
	 * A String Comparator that is used in this project.
	 * Compares Strings in a non-case-sensitive way
	 * @author Felix Pusch
	 *
	 */
	private class FileNameComparator implements Comparator<String> {
		@Override
		public int compare(String s1, String s2) {
			return s1.toLowerCase(Locale.getDefault()).compareTo(s2.toLowerCase(Locale.getDefault()));
		}
		
	}
}
